<!-- 交易市场管理 -->
<template>
  <div>
    <ContainerSlot>
      <template slot="searchModule">
        <SearchForm :label-width="labelWidth" :form-config="formConfig" :form-data="formData" :slot-list="slotList">
          <template slot="searchBtn">
            <el-button type="primary" @click.prevent="search()">查询</el-button>
          </template>
        </SearchForm>
      </template>

      <template slot="operationModule">
        <el-button type="primary" plain  @click="add">添加</el-button>
        <el-button type="danger"  plain  @click="delSelectData"> 删除 </el-button>
        <el-button type="success" plain  @click.prevent="toImport()">导入</el-button>
      </template>

      <template slot="contentModule">
        <Table :prop-list="propList" :list-data="tableData" @handleSelectionChange="handleSelectionChange">
          <template slot="marketname" slot-scope="{ row }">{{ { ...row.market }.name }}</template>
          <!-- 水产品 -->
          <template slot="aquaticproduct" slot-scope="{ row }">
            <span v-for="(item, index) in row.goodsList" :key="index">
              {{ item.goodsName}}{{ item.unitName ? `/${item.unitName}` : "" }}；
              </span>
          </template>

          <template slot="operation" slot-scope="{ row }">
            <el-button class="opt" type="primary" v-show="row.market" plain @click="edit(row)"><i class="el-icon-edit-outline"></i>编辑</el-button>
            <el-button class="opt" type="danger" v-show="row.market" plain @click="del(row)"><i class="el-icon-delete"></i>删除</el-button>
            <el-button type="success" v-show="row.market" plain  @click.prevent="toImport(row)">导入</el-button>
            <el-button type="warning" v-show="row.market" plain  @click.prevent="download(row)">下载模板</el-button>
          </template>
        </Table>
      </template>
      <!-- 分页器 -->
      <template slot="footerModule">
        <el-pagination :current-page="currentPage" background :page-size="pageSize" :page-sizes="[10, 20, 30]" 
          layout=" prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </template>
    </ContainerSlot>

    <!-- 对话框 -->
    <el-dialog :close-on-click-modal='false' :title="`市场${title}`" :visible.sync="dialogFormVisible" top="30vh" @close="cancle">
      <!-- 表单收集 -->
      <el-form ref="ruleForm" :inline="true" :model="toform" :rules="rules">
        <el-form-item label="市场名称：" :label-width="formLabelWidth" class="formItem" prop="market.name">
          <el-input v-model="toform.market.name" placeholder="请输入" clearable></el-input>
        </el-form-item>

        <!-- :prop="!toform.goodsList.length ? 'aquaticProductFont' : ''" class="formItem formItem02" -->
        <!-- :prop="!toform.goodsList.length ? 'toformUnits' : ''" class="formItem formItem03" -->
        <div class="apfUnitsInput">
          <el-form-item label="水产品：" :label-width="formLabelWidth" class="formItem formItem02">
            <img src="@/assets/form_Images/Required.png" alt="">
            <el-input v-model="aquaticProductFont" placeholder="请输入水产品" ref="aProduct" clearable 
              @blur="aquaticProductFont=$event.target.value.trim()">
            </el-input>
          </el-form-item>

          <el-form-item label="" :label-width="formLabelWidth" prop="diagnosisItemId" class="UnitADD">
            <el-select v-model="toformUnits" placeholder="请选择单位" clearable @change='currentUnit'>
              <el-option v-for="item of Units"  
                :key="item.unitId"
                :label="item.unitName"
                :value="item.unitName" />
            </el-select>
            <el-button @click.prevent="addAquaticProduct">添加</el-button>
          </el-form-item>
        </div>
      </el-form>

      <!-- 水产品添加的每一项 -->
      <div class="addAquaticProduct">
        <div v-for="(item, index) in toform.goodsList" :key="index">
          {{ item.goodsName }}/{{ item.unitName }}
          <i class="el-icon-circle-close" @click="delIcon(item,index)"></i>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="save('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 文件导入 -->
    <UploadExcel v-if="uploadShow" ref="uploadRef" @refresh="search"></UploadExcel>
  </div>
</template>

<script>
import ContainerSlot from "@/components/Container";
import SearchForm from "@/components/Form";
import Table from "@/components/Table";
import TradingMarketManagement from "@/api/market-quotation/trading-market-management/index";      // 交易市场管理
import TMQuaticProduct from "@/api/market-quotation/trading-market-management/tmQuaticProduct.js"; // 交易市场水产品独立接口
import UnitsManagement from '@/api/module/units-management'                                        // 单位管理
import UploadExcel from "./upload-excel.vue";  // 导入

export default {
  name: "",
  components: { ContainerSlot, SearchForm, Table, UploadExcel },
  data() {
    return {
      // 查询栏 - 表单数据
      formData: {
        name: "", // 市场名称
      },
      // 查询栏 - 表单配置
      formConfig: [
        {label: "市场名称",prop: "name",type: "input",width: "150px",},
      ],
      uploadShow: false,
      labelWidth: "100px",
      // 插槽
      slotList: [
        {slotName: "searchBtn",},
      ],
      // 添加/修改 - 表单
      toform: {
        market: {
          name: "",              // 市场名称
        },
        goodsList: [],           // 水产品+单位
      },
      aquaticProductFont: "",   // 水产品输入框文字
      toformUnits: "",          // 单位输入框文字
      title: "添加",
      dialogFormVisible: false,
      formLabelWidth: "120px",
      editRowMarketId:null,  // 点击修改时当前行的marketId
      editRowRow:null,       // 点击修改时当前行的数据row
      // 添加/修改时 - 是否请求水产品独立接口
      isAddorEdit:false,
      // 表单验证
      rules: {
        "market.name": [
          { required: true, message: "请输入", trigger: ["blur"] },
        ],
      },
      // 表格
      propList: [
        { label: "市场名称", minWidth: "120", slotName: "marketname" },
        { label: "水产品", minWidth: "180", slotName: "aquaticproduct" },
        { label: "操作", minWidth: "180", slotName: "operation" },
      ],
      tableData: [],
      Units:[],        // 单位管理全部数据
      UnitsId:null,    // 当前单位的id
      idList: [],      // 表格所选行的id数组，用于批量删除；
      // 分页
      total: 1,        // 总条数
      currentPage: 1,  // 当前页
      pageSize: 10,    // 每页条数
    };
  },
  created() {
    this.getTradingMarket(); // 获取交易市场
    this.getUnit()           // 获取单位
  },
  mounted() {},
  methods: {
    // 查询
    search() {
      this.currentPage = 1;
      this.getTradingMarket();
    },
    // 获取交易市场
    async getTradingMarket() {
      let params = {
        page: this.currentPage,   // 当前页
        size: this.pageSize,      // 每页条数
        condition: this.formData,
      };
      let res = await TradingMarketManagement.queryPageByCondition(params);
      console.log("获取交易市场查询", res);
      if (res.code == 200) {
        this.tableData = res.data.content;
        this.total = res.data.totalElements;
      } else {
        this.$message.error(res.code);
      }
    },
    // 获取单位管理
    async getUnit(){
      let res=await UnitsManagement.queryPageByCondition({page:1,size:10000})
      console.log('获取到的单位',res);
      if (res.code==200) {
        this.Units=res.data.content
        console.log('获取到的单位this.Units',this.Units);
      }
    },
    // 单位下拉框
    currentUnit(e){
      console.log('单位下拉框',e);
       let obj = {}
      // 找到选中项的整个object对象
      obj = this.Units.find(item => {
          return item['unitName'] === e
      });
      // 获取对应的id
      this.UnitsId=obj.unitId
      console.log('当前选项的单位id',this.UnitsId);
    },
    // 当前页
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getTradingMarket();
      console.log(`当前第${e}页`);
    },
    //
    handleSizeChange(e) {
      this.pageSize = e;
    },
    
    // 添加操作
    add() {
      // isAddorEdit=false 不请求水产品独立接口
      this.isAddorEdit=false
      console.log(this.tableData);
      this.title = "添加";
      this.dialogFormVisible = true;
      this.toform = {
        market: {
          name: "", // 市场名称
        },
        goodsList: [], // 水产品
      };
      this.toform.goodsList.length = 0;
    },
    // 编辑操作
    edit(row) {
      console.log(row);
      this.title = "修改";
      this.dialogFormVisible = true;
      this.toform = JSON.parse(JSON.stringify({ ...row }));
      //isAddorEdit=true 请求水产品独立接口
      this.isAddorEdit=true 
      this.editRowRow=row // 修改时获取当前行的数据
      this.editRowMarketId=row.market.marketId // 修改时获取当前行的marketId
    },

    // 对话框 - 添加水产品
    addAquaticProduct() {
      // 如果当前为添加操作
      if (!this.isAddorEdit) {        
        if (this.aquaticProductFont&&this.toformUnits) {
          this.toform.goodsList.push({goodsName: this.aquaticProductFont,unitName:this.toformUnits,unitId:this.UnitsId});
          this.aquaticProductFont = "";
          this.toformUnits = "";
        } 
        else {
          this.$message.error("请完整输入 水产品/单位！");
        }
      }
      // 如果当前为编辑操作 
      if (this.isAddorEdit) {
        if (this.aquaticProductFont&&this.toformUnits) {
          this.addTMQuaticProduct() // 调用水产品独立接口进行 添加水产品+单位
        } 
        else {
          this.$message.error("请完整输入 水产品/单位！");
        }
      }
    },
    // 编辑时 - 添加水产品的接口
    addTMQuaticProduct(){
      TMQuaticProduct.add({marketId:this.editRowMarketId,goodsName:this.aquaticProductFont,unitId:this.UnitsId}).then((res)=>{
        if (res.code==200) {
          this.$message.success('修改-添加 成功！')
          console.log('修改操作 - 添加水产品',res.data);
          this.toform.goodsList.push({
            goodsName: this.aquaticProductFont,unitName:this.toformUnits,unitId:this.UnitsId,goodsInMarketId:res.data.goodsInMarketId
          });
          this.aquaticProductFont = "";
          this.toformUnits = "";
          console.log('添加之后的this.editRowRow',this.editRowRow);
        }else{
          this.$message.error(res.msg)
        }
      })
    },

    // 对话框 - 删除水产品
    delIcon(item,index) {
      // 如果当前为添加操作
      if (!item.goodsInMarketId) {        
        this.toform.goodsList.splice(index, 1);
        return 
      }
      // 否则为编辑操作 - 调用水产品独立接口：删除水产品/单位
      this.editTMQuaticProduct(item.goodsInMarketId,index) 
    },
    // 编辑时 - 删除水产品的接口
    editTMQuaticProduct(goodsInMarketId,index){
      console.log('****************************');
      if (this.toform.goodsList.length==1) {
        this.$message.error('至少添加一种水产品！！！')
        return
      }
      this.$confirm("此操作将永久删除该市场下此产品！ 是否继续?", "提示",{confirmButtonText: "确定",cancelButtonText: "取消",type: "warning",})
        .then(async () => {
          let res = await TMQuaticProduct.delById(goodsInMarketId);
          if (res.code == 200) {
            this.$message.success('删除成功！')
            this.toform.goodsList.splice(index, 1);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },

    // 添加/修改操作 - 提交
    save() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // delete this.toform.aquaticProductFont; // 删除水产品输入框字段
          // delete this.toform.toformUnits;        // 删除单位输入框字段
          if(!this.toform.goodsList.length){
            this.$message.error('请添加 水产品/单位！')
            return
          }
          if (this.title === "添加") {
            let res = await TradingMarketManagement.add(this.toform);
            if (res.code == 200) {
              this.$message.success("添加成功！");
              this.getTradingMarket();
              this.dialogFormVisible = false; // 关闭对话框
            }
            console.log(res);
          }
          if (this.title === "修改") {
            let res = await TradingMarketManagement.edit(this.toform);
            if (res.code == 200) {
              this.$message.success("修改成功！");
              this.getTradingMarket();
              this.dialogFormVisible = false; // 关闭对话框
            }
          }
        } else {
          return false;
        }
      });
    },
    // 删除单条数据
    del(row) {
      console.log("当前删除的", row);
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示",{confirmButtonText: "确定",cancelButtonText: "取消",type: "warning",})
        .then(async () => {
          let res = await TradingMarketManagement.delById({marketId: row.market.marketId,});
          console.log("---", res);
          if (res.code == 200) {
            if (this.total % this.pageSize == 1 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.getTradingMarket();
            this.$message({ type: "success", message: "删除成功!" });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    // 当表格的选择项发生变化时触发
    handleSelectionChange(selectData) {
      this.idList = [];
      selectData.forEach((item) => {
        item.market.marketId && this.idList.push(item.market.marketId);
        console.log("当前的item.market.marketId", item.market.marketId);
      });
      console.log("this.idList", this.idList);
    },
    // 批量删除
    delSelectData() {
      if (!this.idList.length) {
        return;
      }
      this.$confirm("您确定删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          TradingMarketManagement.delListById(this.idList).then((res) => {
            if (res.code == 200) {
              this.getTradingMarket();
              this.$message({ type: "success", message: "删除成功!" });
            } else {
              this.$message.error(res.code);
            }
          });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    // 取消按钮
    cancle() {
      // if (this.toform.goodsList.length===0) {
      //   this.$message.error('至少添加一条水产品！')
      //   return
      // }
      this.dialogFormVisible = false;
      this.aquaticProductFont = "";
      this.toform = {
        market: {
          name: "",    // 市场名称
        }, 
        goodsList: [], // 水产品
      };
      this.toformUnits = "";
      this.$refs.ruleForm.resetFields(); // 清空表单验证
      this.getTradingMarket();
    },
    // 下载模板
    async download(row) {
      console.log('下载模板的row',row);
      // const res = await TradingMarketManagement.fileDownload();
      const res = await TradingMarketManagement.fileDownload(row.market.marketId);
      let url = window.URL.createObjectURL(new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
      let link = document.createElement('a') // 创建a标签来下载
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', `${row.market.name}模板`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 导入
    toImport(row) {
      this.uploadShow = true;
      this.$nextTick(() => {
        this.$refs.uploadRef.init(row);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// dialog框header背景色
::v-deep .el-dialog__header {
  background: #0480fb;
}
// 设置dialog框叉号颜色
::v-deep .el-dialog__close {
  color: #fff;
}
// dialog框标题颜色
::v-deep .el-dialog__title {
  color: #fff;
}
::v-deep .el-form-item__label {
  /* width: 0px; */
}
/* 每一项el-form-item */
::v-deep .formItem {
  display: flex;
}
::v-deep .formItem label {
  width: 100px !important;
  padding: 0px;
  display: flex;
  justify-content: flex-end;
}
::v-deep .formItem > * {
  display: flex;
}
/* 水产品+单位 */
.apfUnitsInput {
  display: flex;
  /* 水产品 */
  ::v-deep .formItem02 {
    position: relative;
    margin-right: 0px;
    img{
      width: 20px;
      position: absolute;
      top: 10px;
      left: -65px;
      width: 6px;
      filter:brightness(1.1)
    }
  }
  /* 单位label */
  ::v-deep .formItem03 label {
    width: 0px !important;
  }
  ::v-deep .UnitADD .el-form-item__content{
    display: flex;
  }
}
/* 单位input */
::v-deep .unitsInput {
  width: 120px;
}
/* 添加水产品-对话框 */
.addAquaticProduct {
  display: flex;
  flex-wrap: wrap;
  div {
    border: 1px solid rgb(218, 218, 242);
    border-radius: 10px;
    padding: 2px 6px;
    margin: 0 6px 6px 0;
  }
}
</style>
